local M = {}

M.logfile = nil
M.log_file_path = nil
M.plugin_dir = nil

-- 初始化日志文件
function M.init_log()
  if M.log_file == nil then
    local script_path = debug.getinfo(1, "S").source:sub(2)
    M.plugin_dir = script_path:match("(.*[/\\])") or ""
    M.log_file_path = M.plugin_dir .. "test.log"
    local success, file = pcall(io.open, M.log_file_path, "a")
    if success then
      M.log_file = file
    else
      vim.api.nvim_err_writeln("无法打开日志文件: " .. M.log_file_path)
    end
  end
end

-- 关闭日志文件
function M.close_log()
  if M.log_file then
    M.log_file:close()
    M.log_file = nil
  end
end

-- 弹出float 窗体，显示日志。Esc 退出
function M:pop_log(log_str)
  -- 创建一个新的临时 buffer
  local buf = vim.api.nvim_create_buf(false, true) -- [listed=false, scratch=true]

  -- 填充内容
  local lines = (type(log_str) == "string") and vim.split(log_str, "\n") or log_str
  vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines)

  -- 创建浮动窗口
  local win = vim.api.nvim_open_win(buf, true, {
    relative = "editor",
    row = 5,
    col = 10,
    width = 80,
    height = 28,
    border = "rounded",
    style = "minimal",
  })

  -- 设置 buffer 属性（只读、无文件）
  vim.bo[buf].buftype = "nofile"
  vim.bo[buf].bufhidden = "wipe"
  vim.bo[buf].swapfile = false
  vim.bo[buf].modifiable = false

  -- 绑定 ESC 关闭窗口
  vim.keymap.set("n", "<Esc>", function()
    if vim.api.nvim_win_is_valid(win) then
      vim.api.nvim_win_close(win, true)
    end
  end, { buffer = buf, nowait = true, silent = true })
end

-- 写入日志
function M:write_log(message)
  if M.log_file == nil then
    M:init_log()
  end
  if M.log_file and message ~= nil then
    local time = os.date("%Y-%m-%d %H:%M:%S")
    M.log_file:write("[" .. time .. "] " .. message .. "\n")
    M.log_file:flush()
  end
end

return M
